package com.huacai.blog.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    @Value("${deepseek.api-key}")
    private String apiKey;

    private final String DEEPSEEK_URL = "https://api.deepseek.com/v1/chat/completions"; // ← 去空格

    @PostMapping("/ask")
    public JSONObject ask(@RequestBody JSONObject req) {
        String question = req.getString("question");
        if (question == null || question.trim().isEmpty())
            return new JSONObject() {{ put("error", "内容不能为空"); }};

        RestTemplate rest = new RestTemplate();
        HttpHeaders h = new HttpHeaders();
        h.setContentType(MediaType.APPLICATION_JSON);
        h.set("Authorization", "Bearer " + apiKey);

        JSONObject body = new JSONObject();
        body.put("model", "deepseek-chat");
        body.put("messages", new JSONArray() {{   // ← 必须是数组
            add(new JSONObject() {{
                put("role", "user");
                put("content", question);
            }});
        }});
        body.put("temperature", 0.7);

        HttpEntity<String> entity = new HttpEntity<>(body.toJSONString(), h);
        String resp = rest.postForObject(DEEPSEEK_URL, entity, String.class);

        JSONObject out = JSONObject.parseObject(resp);
        String answer = out.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");
        return new JSONObject() {{ put("answer", answer.trim()); }};
    }
}